package com.ming.config;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ming.constant.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @Author:何元才
 * @Desc: 代码方式的路由
 * 目的是拿到登陆的响应值
 * 存入redis
 */
@Configuration
public class RouteConfig {


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 路由存放token
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder){
        RouteLocatorBuilder.Builder routes = builder.routes();
        routes.route("oauth-server-router",r->r.path("/oauth/token")
                    .filters(f->f.modifyResponseBody(String.class, String.class,
                            (exchange, s) -> {
                                //拿到登陆响应值
                                JSONObject jsonObject = JSONUtil.parseObj(s);
                                String accessToken = jsonObject.getStr("access_token");
                                if (StringUtils.hasText(accessToken)) {
                                    // 登录成功了
                                    // 拿到过期时间
                                    Long expiresIn = jsonObject.getLong("expires_in");
                                    // 存入redis
                                    redisTemplate.opsForValue().set(GatewayConstant.TOKEN_JWT_PREFIX + accessToken, "", Duration.ofSeconds(expiresIn));
                                }
                                return Mono.just(s);
                            })).uri("lb://auth-server"));
        return routes.build();
    }
}
